package com.gitee.fanx.sample.otpauth.service.impl;

import com.gitee.fanx.sample.otpauth.common.TotpAuthenticator;
import com.gitee.fanx.sample.otpauth.dao.UserStore;
import com.gitee.fanx.sample.otpauth.entity.User;
import com.gitee.fanx.sample.otpauth.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.*;

/**
 * @author fanhang
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserStore userStore;
	@Autowired
	private TotpAuthenticator totpAuthenticator;

	@Override
	public User register(String phone) {
		String secret = totpAuthenticator.generateSecret(phone);
		User user = new User();
		user.setPhone(phone);
		user.setTotpSecret(secret);
		this.userStore.put(phone, user);
		return user;
	}

	@Override
	public int verify(String phone, Integer code) {
		User user = this.userStore.get(phone);
		Assert.notNull(user, "用户不存在");
		return totpAuthenticator.validCode(user.getTotpSecret(), code);
	}

	@Override
	public String generateTotpauthUri(String phone) {
		User user = this.userStore.get(phone);
		Assert.notNull(user, "用户不存在");
		try {
			return totpAuthenticator.generateUri(phone);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public List<User> getAll() {
		return this.userStore.all();
	}
}
